package com.cssl.utils;

import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.jms.Destination;
import javax.jms.ObjectMessage;
import java.io.Serializable;

@Component
public class ActiveMQUtils {

    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 发送队列消息和yml配置消息类型无关
     * @param queue 队列名
     * @param message 消息内容
     */
    public void sendQueueMessage(String queue, final Object message){
        Destination destination=new ActiveMQQueue(queue);
        jmsTemplate.convertAndSend(destination, message);
    }

    /**
     * 发送主题消息和yml配置消息类型无关
     * @param topic 主题名
     * @param message 消息内容
     */
    public void sendTopicMessage(String topic, final Object message){
        Destination destination=new ActiveMQTopic(topic);
        jmsTemplate.convertAndSend(destination, message);
    }

    /**
     * 延时队列
     * @param queue 队列名
     * @param msg   消息内容，必须实现序列化
     * @param delay 单位毫秒
     */
    public void sendDelayQueue(String queue, Serializable msg, long delay) {
        Destination destination=new ActiveMQQueue(queue);
        jmsTemplate.send(destination, session -> {
            ObjectMessage objectMessage = session.createObjectMessage(msg);
            objectMessage.setLongProperty(
                    ScheduledMessage.AMQ_SCHEDULED_DELAY,delay);
            return objectMessage;
        });
    }

    /**
     * 延时主题
     * @param topic 主题名
     * @param msg 消息内容，必须实现序列化
     * @param delay 单位毫秒
     */
    public void sendDelayTopic(String topic, Serializable msg, long delay) {
        Destination destination=new ActiveMQTopic(topic);
        jmsTemplate.send(destination, session -> {
            ObjectMessage objectMessage = session.createObjectMessage(msg);
            objectMessage.setLongProperty(
                    ScheduledMessage.AMQ_SCHEDULED_DELAY,delay);
            return objectMessage;
        });
    }
}
